from typing import List,Union,Optional,Dict,Literal
from nicegui import ui,binding
import SqliteHelper as sqlhp
import utils

class SearchAbleSelect():
    value:Union[str,None]=binding.BindableProperty()
    is_selected:Union[str,None]=binding.BindableProperty()
    def __init__(self,value:Union[str,None]=None,options:List=[],label:str='',selected_obj:List=None,disease_or_surgery:Literal['disease','surgery']='disease',db_conect_str:str='',limit:int=50):
        self.value=value
        self.label=label
        self.selected_obj=selected_obj
        self.db_conect_str=db_conect_str if  db_conect_str else r'data/drg_grouper_main.db'
        # self.sql_where=sql_where
        self.db_sheet=disease_or_surgery if disease_or_surgery in ['disease','surgery'] else 'disease'
        self.limit=limit
        self.options=options
        self.value=None
        # self.checkbox:Union[ui.Checkbox,None]=None
        self.is_selected=False
        self.__search_text=''

        self.input_select=ui.select(options=self.options,label=self.label,with_input=True,clearable=True).props('dense option-dense').bind_value(self, 'value')
        with self.input_select.add_slot('prepend'):
            ui.checkbox().bind_value(self, 'is_selected').props('dense').on('click',self.__on_checkbox_click)
        self.input_select.on('filter',lambda e: self._on_filter(e.args[0]))
        # self.input_select.on('input',self.__on_input)
        # self.input_select.on('input-value',lambda e: self.__on_input_value(e.args))
            


    def __search(self,text:str)->List[str]:
        if not text:
            return []
        db=sqlhp.Connect(self.db_conect_str)
        ret=db.table(self.db_sheet).where(f'CODENAME LIKE "%{text}%"').field('CODENAME').find(self.limit)
        ret=[item['CODENAME'] for item in ret]
        ret_sorted=utils.sort_list_by_similarity(ret,text) if ret else []
        return ret_sorted
    
    # def __on_input_value(self,value:str)->None:
    #     self.__search_text=value.strip()
    #     print(f'input_value: {value}')

    # def __on_input(self)->None:
    #     options=self.__search(self.__search_text)
    #     self.set_options(options)
    #     print(f'self.__search_text:{self.__search_text}')

    def _on_filter(self,text:str)->None:
        self.__search_text=text.strip()
        options=self.__search(self.__search_text)
        self.set_options(options)


    def __on_checkbox_click(self)->None:
        if  self.selected_obj is None: 
            return
        if  not isinstance(self.selected_obj[0],SearchAbleSelect):
            self.selected_obj[0]=self
        elif self.selected_obj[0] != self:
            self.selected_obj[0].is_selected=False
            self.selected_obj[0]=self
        elif not self.is_selected:
            self.selected_obj[0]=0
        # self.is_selected=True
        # ui.notify(f'{self.selected_obj[0]} is selected')

    
    def set_options(self,options:List)->None:
        self.options=options
        self.input_select.set_options(self.options)

